<!-- waring 拷贝相关工单类型创建 偷懒方法名也不想改了 -->
<template>
  <base-modal
    :title="title"
    width="672px"
    @cancel="cancel"
    :show.sync="isShow"
    :mask-closeable="false">
    <div v-if="!clickTaskType" class="add-type-box">
      <el-row type="flex" justify="space-between">
        <el-card
          class="choose-type-box"
          :class="getCardActive(item.type) && 'active'"
          :style="{'background-image': 'url(' + item.bgImg + ')'}"
          v-for="item in taskTemplateList"
          :key="item.type"
          shadow="hover"
          @click.native="chooseTypeTemplate(item.type)"
          @mouseenter.native="enterCard(item.type)"
          @mouseleave.native="hoverTaskType = ''"
        >
          <div class="choose-type-box-content">
            <h2>{{item.title}}</h2>
            <p class="task-type-desc">{{item.desc}}</p>
          </div>
        </el-card>
      </el-row>
    </div>
    <el-form label-position="top" v-else :model="form" :rules="rules" ref="form" class="add-type-form" onsubmit="return false;">
      <el-form-item v-if="clickTaskType === 'exist'" :label="'合同类型'" prop="templateId">
        <el-select v-model="form.templateId" :placeholder="$t('common.placeholder.selectSomething', {0: '合同类型'})" class="w-360">
          <el-option
            v-for="item in contractList"
            :key="item.id"
            :label="item.templateName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('common.base.name')" prop="templateName">
        <el-input class="w-360" v-model="form.templateName" :placeholder="$t('task.setting.taskTypeSetting.manage.tip1')"></el-input>
        <!-- <base-select-language 
            :field="{}"
            :defaultValueLanguage = "form.nameLanguageMap"
            :defaultValue="form.typeName"
            @save = "save"
          ></base-select-language> -->
      </el-form-item>
      <el-form-item>
        <ul class="statecolor">
          <li
            v-for="color in taskTypeColor"
            :key="color"
            @click="form.color = color"
            :style="{ background: color}">
            <i class="el-icon-check" v-if="color === form.color"></i>
          </li>
        </ul>
      </el-form-item>
    </el-form>

    <div v-if="clickTaskType" slot="footer">
      <el-button @click="cancel">{{$t('common.base.cancel')}}</el-button>
      <el-button :loading="pedding" type="primary" @click="createTaskType">{{$t('common.base.makeSure')}}</el-button>
    </div>

    <!-- 选择行业模板弹窗 -->
    <choose-trade-dialog :visiable.sync="isShowChooseTradeDialog" @select="selectTemplate"/>
  </base-modal>
</template>

<script>
/** api */
import * as SettingApi from '@src/api/SettingApi.ts';
import { saveCopyContractTemplate} from '@src/api/ContractApi.ts';

// assets
import { getOssUrl } from '@src/util/assets'
const taskTemplateBlank = getOssUrl('/setting/task-template-blank.png');
const taskTemplateCopy = getOssUrl('/setting/task-template-copy.png');
const taskTemplateTrade = getOssUrl('/setting/task-template-trade.png');

// components
import ChooseTradeDialog from './ChooseTradeDialog.vue';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'
const TASK_TYPE_COLOR = [
  'rgb(115,127,124)',
  'rgb(38,111,255)',
  'rgb(82,85,255)',
  'rgb(133,82,255)',
  'rgb(188,82,255)',
  'rgb(255,82,212)',
  'rgb(255,149,38)',
  'rgb(110,207,64)',
  'rgb(0,184,213)',
  'rgb(11,161,148)'
];

export default {
  name:'add-type-dialog',
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    contractList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    let validateTypeName = (rule, value, callback) => {
      if (value === '') return callback(new Error(i18n.t('task.setting.taskTypeSetting.flow.placeholder1')));
      if(value.length > 100) callback(new Error(i18n.t('common.validate.nameLimit', {limit: '100'})));
      // if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) return callback(new Error(i18n.t('task.setting.taskTypeSetting.manage.tip3')));

      callback();
    };

    return {
      hoverTaskType: '',
      clickTaskType: '',

      form: {
        templateName: '',
        // taskTypeId: '',
        templateId: '',
        color: 'rgb(115,127,124)',
        nameLanguageMap:{}
      },
      rules: {
        taskType: [{ required: true, message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('common.task.taskType')}), trigger: 'blur' }],
        templateName: [
          { required: true, message: i18n.t('contract.setting.contractTemplate.text3'), trigger: 'blur' },
          { validator: validateTypeName, trigger: 'blur' }
        ]
      },
            
      pedding: false,
      isShow: false,
      isShowChooseTradeDialog: false,
    }
  },
  computed: {
    taskTypeColor() {
      return TASK_TYPE_COLOR;
    },
    title() {
      return this.clickTaskType 
        ? this.taskTemplateList.find(item => item.type === this.clickTaskType).title
        : this.$t('contract.setting.contractTemplate.text9');
    },
    taskTemplateList() {
      return [
        {
          type: 'blank',
          title: i18n.t('common.base.createFromBlankTemplate'),
          desc: this.$t('contract.setting.contractTemplate.createNewTemplate'),
          bgImg: taskTemplateBlank
        },
        {
          type: 'exist',
          title: i18n.t('task.setting.taskTypeSetting.manage.title7'),
          desc: i18n.t('task.setting.taskTypeSetting.manage.desc2'),
          bgImg: taskTemplateCopy
        },
        {
          type: 'template',
          title: i18n.t('task.setting.taskTypeSetting.manage.title8'),
          desc: i18n.t('task.setting.taskTypeSetting.manage.desc3'),
          bgImg: taskTemplateTrade
        },
      ]
    }
  },
  watch: {
    visiable(newVal){
      this.isShow = newVal;

    }
  },
  methods: {
    enterCard(type) {
      this.hoverTaskType = type;
    },
    getCardActive(type) {
      return this.hoverTaskType === type;
    },
    cancel() {
      let _this = this;
      this.$emit('update:visiable', false);
      setTimeout(() => {
        Object.assign(this.$data, this.$options.data());
        _this.$refs.form.resetFields();
      }, 100)
    },
    /** 选择行业模板 */
    selectTemplate({id, typeName, contractTypeNameLanguage}) {
      this.clickTaskType = 'template';
      this.form = {
        ...this.form,
        templateName: typeName,
        templateId: id,
        nameLanguageMap: contractTypeNameLanguage
      }
    },
    /** 选择新建类型 */
    chooseTypeTemplate(type) {
      if(type === 'template') {
        return this.isShowChooseTradeDialog = true;
      }

      this.clickTaskType = type;
    },
    /**
         * 创建工单
         */
    createTaskType() {
      this.$refs.form.validate(valid => {
        if(valid) {
          let fromId = window.frameElement?.getAttribute('id') || '';
          const params = { ...this.form }
          if(this.clickTaskType === 'template') {
            params.isSystemTemplate = true
          } else {
            params.isSystemTemplate = false
          }

          if(this.clickTaskType === 'blank') return this.$emit('submitSave', params)
          // 从空白模板/现有工单类型创建
          this.pedding = true;
          saveCopyContractTemplate(params).then(res => {
            if(res.status == 0){
              openAccurateTab({
                type: PageRoutesTypeEnum.PageContractFlowSetting,
                closeNowPage: true,
                params: `id=${res.result}`,
                fromId,
              })
              let id = window.frameElement.dataset.id;
              this.$platform.refreshTab(id);
            }else{
              this.$platform.alert(res.message);
              // if(this.clickTaskType === 'template') { 
              //   this.clickTaskType = ''
              //   this.form = {
              //     templateName: '',
              //     templateId: '',
              //     color: 'rgb(115,127,124)',
              //     nameLanguageMap:{}
              //   }
              // }
            }
          }).catch(err => {
            console.error(err);
          })
            .finally(() => {
              this.pedding = false;
            });
        }
      })
    },

    save(form) {
      this.form.nameLanguageMap = form;
      this.form.typeName = form[i18n.locale];
    }
  },
  components: {
    [ChooseTradeDialog.name]: ChooseTradeDialog
  }
}
</script>

<style lang="scss" scoped>
.add-type-box{
    max-height: 403px;
    padding: 40px 40px 20px 40px;
    overflow: hidden;
    .choose-type-box{
        cursor: pointer;
        position: relative;
        width: 183px;
        height: 244px;
        border-radius: 10px;

        background-repeat: no-repeat;
        background-position: center center;
        background-size: cover;

        &.active{
            .choose-type-box-content{
                transform: translateY(0);
                p{
                    opacity: 1;
                }
            }
        }

        .choose-type-box-content{
            position: absolute;
            left: 16px;
            bottom: 17px;
            color: #FFFFFF;
            transform: translateY(22px);
            transition: all .5s ease;

            h2{
                margin-bottom: 5px;
                font-size: 16px;
            }
            p{
                margin-bottom: 0;
                font-size: 12px;
                opacity: 0;
                transition: all .5s ease;
            }

        }
    }
}

.add-type-form{
    padding: 20px;
    ul.statecolor{
        padding: 0;
        line-height: 22px;
        li{
            list-style: none;
            display: inline-block;
            cursor: pointer;
            margin-right: 4px;
            width: 32px;
            height: 22px;
            vertical-align: middle;
            i{
                position: relative;
                font-weight: bold;
                left: 9px;
                color: #fff;
            }
        }
    }
}

.w-360{
    width: 360px;
}
</style>